<template>
  <div :id="props.domId" class="pieChar"></div>
</template>

<script setup name="pieChart">
import * as echarts from "echarts";
const { proxy } = getCurrentInstance();
const props = defineProps({
  domId: {
    type: String,
    default: "",
  },
  api: {
    type: Function,
    default: undefined,
  },
  title: {
    type: String,
    default: "",
  },
  vueRouterName: {
    type: String,
    default: "",
  },
});

const option = ref({});
const timeInterval = ref("");

onMounted(() => {
  init();
});

const init = () => {
  props.api().then((res) => {
    if (res) {
      let data = res.data.series[0].data;
      let legendData = res.data.legend.data;
      option.value = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "horizontal",
          x: "left",
          data: legendData,
        },
        series: [
          {
            name: computed(()=>{return props.title}),
            type: "pie",
            radius: ["50%", "70%"],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: "center",
              },
            },
            labelLine: {
              normal: {
                show: false,
              },
            },
            data: data,
          },
        ],
      };
      let echart = echarts.init(document.getElementById(props.domId));
      echart.setOption(option.value);
      echart.on("click", function (_params) {
        console.log(_params)
        if (props.vueRouterName) {
          proxy.$router.push({
            name: props.vueRouterName,
            params: {..._params, paramsData: JSON.stringify(_params.data)}
          });
        }
      });
      window.addEventListener("resize", () => {
        echart.resize();
      });
    }
  });
};
</script>

<style scoped>
.pieChar {
  height: calc(100% - 34px);
  padding-top: 10px;
  display: flex;
  justify-content: center;
}
</style>
